package com.chainyoung.component_tmperson.ui.fragment;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetBehavior;
import android.support.design.widget.BottomSheetDialog;
import android.support.design.widget.BottomSheetDialogFragment;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chainyoung.common.appcommon.entity.HdWallet;
import com.chainyoung.common.appcommon.entity.HdWalletCache;
import com.chainyoung.common.appcommon.hdwallet.ExchangeCalculator;
import com.chainyoung.component_tmperson.R;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;

public class WebTransactionPayFragment extends BottomSheetDialogFragment {


    private TextView btnCancel;
    private TextView btnConfirm;
    private TextView tvNum;
    private TextView tvBalance;
    private TextView tvFromAddr;
    private TextView tvToAddr;
    private TextView tvFee;
    private TextView tvFeeCacultor;
    private RelativeLayout rlAdjust;
    private TextView tvDAppName;

    private String option;

    private OptionListener onOptionListener;

    private String toAddr, dAppName = "收款账户";
    private BigInteger num;//交易数量 单位 wei


    private HdWalletCache hdWallet;

    private BigDecimal gasPrice = BigDecimal.valueOf(3);

    private BigDecimal oriGasLimit = BigDecimal.valueOf(700000);//gaslimit


    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.tv_cancel) {
                if (onOptionListener != null) {
                    onOptionListener.onCancelTrade(true);
                }
                dismiss();
            } else if (v.getId() == R.id.tv_confirm) {
                if (onOptionListener != null) {
                    onOptionListener.onConfirmTrade();
                }

            } else if (v.getId() == R.id.rl_adjust_fee) {
                //选择
                if (onOptionListener != null) {
                    onOptionListener.onAdjustFee(gasPrice, oriGasLimit);
                }

            }

        }
    };

    private boolean isCanceledTrade = true;

    public void close(boolean isCanceledTrade) {
        this.isCanceledTrade = isCanceledTrade;
        dismiss();
    }

    public void setIsCanceledTrade(boolean canceledTrade) {
        isCanceledTrade = canceledTrade;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
//        final Activity parent = getActivity();
//        if (parent != null) {
//            onOptionListener = (OptionListener) parent;
//        } else {
//            onOptionListener = (OptionListener) context;
//        }
    }

    @Override
    public void onDetach() {
        if (isCanceledTrade) {
            if (onOptionListener != null) {
                onOptionListener.onCancelTrade(false);
            }
        }
        onOptionListener = null;
        super.onDetach();
    }


    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        BottomSheetDialog bottomSheetDialog = (BottomSheetDialog) super.onCreateDialog(savedInstanceState);
        View view = LayoutInflater.from(getContext()).inflate(R.layout.layout_web_transaction_pay_fragment, null);
        bottomSheetDialog.setContentView(view);
        bottomSheetDialog.setCancelable(false);
        bottomSheetDialog.setCanceledOnTouchOutside(false);
        btnCancel = view.findViewById(R.id.tv_cancel);
        btnConfirm = view.findViewById(R.id.tv_confirm);
        tvNum = view.findViewById(R.id.tv_num);
        tvBalance = view.findViewById(R.id.tv_balance);
        tvFromAddr = view.findViewById(R.id.tv_from_addr);
        tvToAddr = view.findViewById(R.id.tv_to_addr);
        tvFee = view.findViewById(R.id.tv_fee);
        tvFeeCacultor = view.findViewById(R.id.tv_fee_caculator);
        tvDAppName = view.findViewById(R.id.tv_dapp_name);
        rlAdjust = view.findViewById(R.id.rl_adjust_fee);
        btnCancel.setOnClickListener(onClickListener);
        btnConfirm.setOnClickListener(onClickListener);
        rlAdjust.setOnClickListener(onClickListener);

        bottomSheetDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {

            }
        });


        try {
            Field mBehaviorField = bottomSheetDialog.getClass().getDeclaredField("mBehavior");
            mBehaviorField.setAccessible(true);
            final BottomSheetBehavior behavior = (BottomSheetBehavior) mBehaviorField.get(bottomSheetDialog);
            behavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
                @Override
                public void onStateChanged(@NonNull View bottomSheet, int newState) {
                    if (newState == BottomSheetBehavior.STATE_DRAGGING) {
                        behavior.setState(BottomSheetBehavior.STATE_EXPANDED);
                    }
                }

                @Override
                public void onSlide(@NonNull View bottomSheet, float slideOffset) {
                }
            });
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        updateView();

        return bottomSheetDialog;
    }

    public void setNumAddr(BigInteger num, String toAddr, HdWalletCache hdWallet, BigDecimal gasPrice, BigDecimal gasLimit, String dappName) {
        this.num = num;
        this.toAddr = toAddr;
        this.hdWallet = hdWallet;
        this.gasPrice = gasPrice;
        this.oriGasLimit = gasLimit;
        this.dAppName = dappName;
        //updateView();
    }

    public void updateView() {

        tvNum.setText(new BigDecimal(num).divide(ExchangeCalculator.ONE_ETHER, 8, RoundingMode.DOWN).stripTrailingZeros().toPlainString() + " ETH");
        tvToAddr.setText(toAddr);
        tvBalance.setText(hdWallet.getBalance() + " ETH");
        tvFromAddr.setText(hdWallet.getAddress());
        tvDAppName.setText(dAppName);

        BigDecimal ethFee = oriGasLimit.multiply(gasPrice).divide(ExchangeCalculator.ONE_GWEI, 8, RoundingMode.DOWN);
        tvFee.setText(String.valueOf(ethFee));
        tvFeeCacultor.setText(String.format("≈Gas(%s)*Gas Price(%s GWEI)", oriGasLimit.setScale(0, RoundingMode.DOWN), gasPrice.setScale(2, RoundingMode.DOWN)));
        BigDecimal total = ethFee.add(new BigDecimal(num).divide(ExchangeCalculator.ONE_ETHER, 8, RoundingMode.DOWN));
        btnConfirm.setText("确定" + String.valueOf(total) + "ETH");


    }

    @Override
    public void show(FragmentManager manager, String tag) {
        if (isAdded()) {
            return;
        }
        super.show(manager, tag);
    }

    public interface OptionListener {

        void onAdjustFee(BigDecimal nowGasPrice, BigDecimal nowGasLimit);

        void onConfirmTrade();

        void onCancelTrade(boolean isNeedDismiss);
    }

    public void setOnOptionListener(OptionListener onOptionListener) {
        this.onOptionListener = onOptionListener;
    }
}
